<template>
    <el-row>
        <el-col :span="4" style="border:1px solid #DCDFE6;height: 100%;">
            <div style="height:30px;padding: 1px 2px 1px 2px;text-align: center;cursor: pointer;margin-bottom:10px;">
                <el-input
                    placeholder="请输入组织机构名称/编码"
                    prefix-icon="el-icon-search"
                    size="small"
                    v-model="selectInput"
                    @input="handleInput">
                </el-input>
            </div>
            <div class="treeBody">
                <el-scrollbar wrap-class="scrollbar-wrap" view-class="scrollbar-view">
                    <el-tree :data="selectDepts" ref="tree"
                             node-key="id"
                             default-expand-all
                             :expand-on-click-node="false"
                             highlight-current
                             @node-click="handleTree"
                             :current-node-key="$store.state.user.deptId"
                             style="padding: 1px 5px 5px 10px;"></el-tree>
                </el-scrollbar>
            </div>
        </el-col>
        <el-col :span="20" style="padding-left:20px;height: 100%;">
            <table-view :showBlockControl="false">
                <template slot="formSlot">
                    <el-form ref="form" :model="form" label-width="80px" :inline="true">
                        <el-form-item label="用户名" prop="userName">
                            <el-input v-model="form.userName" size="small" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="昵称" prop="nickName">
                            <el-input v-model="form.nickName" size="small" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="角色" prop="roleId">
                            <el-select v-model="form.roleId" placeholder="请选择角色" size="small" clearable>
                                <el-option v-for="(item,index) in roles" :label="item.label" :value="item.value"
                                           :key="index"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </template>

                <div slot="btnBeforeSlot">
                    <el-button type="info" plain icon="el-icon-document-add" size="small" @click="handleCustomAdd">新增
                    </el-button>
                </div>
                <div slot="btnAfterSlot">
                    <el-button type="info" plain icon="el-icon-search" size="small" @click="handleSearch">查询</el-button>
                    <el-button type="info" plain icon="el-icon-s-release" size="small" @click="handleRest">重置
                    </el-button>
                </div>

                <template slot="tableSlot">
                    <el-table v-loading="loading" :data="tableData" stripe Checkbox height="100%" size="small"
                              width="100%" @selection-change="handleTableCheckbox">
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column prop="userName" label="用户名"></el-table-column>
                        <el-table-column prop="nickName" label="昵称"></el-table-column>
                        <el-table-column prop="phone" label="手机号"></el-table-column>
                        <el-table-column prop="email" label="邮箱"></el-table-column>
                        <el-table-column prop="deptName" label="部门名称" width="150"></el-table-column>
                        <el-table-column prop="type" label="用户类型" width="120">
                            <template slot-scope="scope">
                                <span v-for="(item,index) in userTypes" v-if="scope.row.type == item.value"
                                      :key="index">{{item.label}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="sex" label="性别" width="120">
                            <template slot-scope="scope">
                                <span v-for="(item,index) in userSexs" v-if="scope.row.sex == item.value" :key="index">{{item.label}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="enabled" label="状态" width="120">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,index) in enableds"
                                        v-if="scope.row.enabled == item.value && scope.row.enabled == enableds[0].value"
                                        :key="index">{{item.label}}
                                </el-tag>
                                <el-tag v-for="(item,index) in enableds"
                                        v-if="scope.row.enabled == item.value && scope.row.enabled == enableds[1].value"
                                        :key="index" type="danger">{{item.label}}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" fixed="right" width="200" align="center">
                            <template slot-scope="scope">
                                <template v-if="$store.getters.user.userName != scope.row.userName">
                                    <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start">
                                        <el-button type="warning" plain size="mini" icon="el-icon-s-custom"
                                                   @click="handleRoleToUser(scope.row)" class="tableBtn">
                                        </el-button>
                                    </el-tooltip>
                                    <el-tooltip class="item" effect="dark" content="修改" placement="top-start">
                                        <el-button type="primary" plain size="mini" icon="el-icon-edit"
                                                   @click="handleCustomAdd(scope.row)" class="tableBtn">
                                        </el-button>
                                    </el-tooltip>
                                    <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                                        <el-button type="danger" plain size="mini" icon="el-icon-delete"
                                                   @click="handleDel(scope.row)" class="tableBtn">
                                        </el-button>
                                    </el-tooltip>
                                    <el-tooltip class="item" effect="dark" content="查看" placement="top-start">
                                        <el-button type="info" plain size="mini" icon="el-icon-search"
                                                   @click="handleDetail(scope.row)" class="tableBtn">
                                        </el-button>
                                    </el-tooltip>
                                </template>
                                <template v-else>
                                    <el-tooltip class="item" effect="dark" content="查看" placement="top-start">
                                        <el-button type="info" plain size="mini" icon="el-icon-search"
                                                   @click="handleDetail(scope.row)" class="tableBtn">
                                        </el-button>
                                    </el-tooltip>
                                </template>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>

                <template slot="paginationSlot">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="page.pageNum"
                        :page-size="page.pageSize"
                        :total="page.total"
                        :page-sizes="[10, 20, 30, 40]"
                        layout="total, sizes, prev, pager, next, jumper">
                    </el-pagination>
                </template>

                <template slot="otherSlot">
                    <dialog-view ref="dialogRef" :title="dialogParams.title" :width="dialogParams.width">
                        <template slot="dialogSlot">
                            <component :is="dialogParams.componentName" :editData="editRow"
                                       @submitSuccess="handleSearch"></component>
                        </template>
                    </dialog-view>
                </template>
            </table-view>
        </el-col>
    </el-row>

</template>

<script>
    import TableView from '@/components/tableView'
    import DialogView from '@/components/dialogView'
    import tableMixin from '@/mixins/table.mixin'
    import {mapActions, mapMutations, mapState} from 'vuex'

    export default {
        mixins: [tableMixin],
        data() {
            return {
                searchApi: this.$api.system.user.list,
                deleteApi: this.$api.system.user.delete,
                title: '用户',
                activeSerach: false,
                form: {
                    userName: '',
                    nickName: '',
                    roleId: ''
                },
                selectInput:'',
                selectDepts: []
            }
        },
        components: {
            TableView,
            DialogView,
            Add: () => import('./add'),
            Detail: () => import('./detail'),
            ToRole: () => import('./toRole'),
        },
        computed: {
            ...mapState('basic', ['deptTrees', 'roles']),
            ...mapState('dic', ['userSexs', 'userTypes', 'enableds'])
        },
        methods: {
            ...mapActions('basic', ['doDeptTreeOfBasic', 'doRolesOfBasic']),
            ...mapActions('dic', ['doUserTypesOfBasic', 'doUserSexsOfBasic', 'doEnabledOfBasic']),
            // 获取table选择项
            handleTableCheckbox(rows) {
                this.deleteBatchData = [];
                rows.forEach(item => {
                    this.deleteBatchData.push(item.id);
                });
            },
            // 角色授权，展示对话框
            handleRoleToUser(row) {
                this.doInitDialog({id: row.id, type: row.type, roleIds: []}, 'ToRole', '分配角色');
            },
            initDatas() {
                // 部门树
                this.doDeptTreeOfBasic().then(result=>{
                    this.selectDepts = [...this.deptTrees]
                });;
                // 角色下拉框
                this.doRolesOfBasic();
                // 数据字典用户类型
                this.doUserTypesOfBasic(this.$appConstant.DIC_CODE.SYSTEM_USERTYPE);
                // 数据字典用户性别
                this.doUserSexsOfBasic(this.$appConstant.DIC_CODE.SYSTEM_SEX);
                // 数据字典启停状态
                this.doEnabledOfBasic(this.$appConstant.DIC_CODE.SYSTEM_ENABLED);
            },
            handleTree(data) {
                this.$store.commit('user/setDeptId', this.$refs.tree.getCurrentKey());
                this.handleSearch();
            },
            handleCustomAdd(row) {
                if (!this.activeSerach || !this.$store.state.user.deptId) {
                    this.$MessageN.warning("请先选择部门");
                    return;
                }
                if (row.constructor.name == 'MouseEvent') {
                    this.handleAdd({enabled: 1, deptId: this.$store.state.user.deptId, type: 0, sex: 0});
                } else {
                    this.handleAdd(row);
                }

            },
            resetSearchParams(search) {
                let nodes = [];
                let node = this.$refs.tree.getCurrentNode();
                // 获取当前节点和子树
                this.doChildrenNode(node, nodes);
                search.deptIds = [...nodes].join(",");
            },
            doChildrenNode(curNode, nodes) {
                nodes[nodes.length] = curNode.id;
                let nextNodes = curNode.children;
                nextNodes.forEach(node => {
                    this.doChildrenNode(node, nodes);
                });
            },
            handleRefreshBtn() {
                this.doDeptTreeOfBasic();
            },
            handleInput(val) {
                this.selectDepts =[];
                for(let i = 0;i < this.deptTrees.length;i++) {
                    if(this.deptTrees[i].label.indexOf(val) != -1 || this.deptTrees[i].value.indexOf(val) != -1) {
                        this.selectDepts.push({...this.deptTrees[i]});
                        return;
                    } else {
                        if(this.deptTrees[i].children && this.deptTrees[i].children.length > 0) {
                            this.searchTree(val, this.deptTrees[i].children);
                        }
                    }
                }
            },
            searchTree(val, deptTrees) {
                for(let i = 0;i < deptTrees.length;i++) {
                    if(deptTrees[i].label.indexOf(val) != -1 || deptTrees[i].value.indexOf(val) != -1) {
                        this.selectDepts.push({...deptTrees[i]});
                        return;
                    } else {
                        if(deptTrees[i].children && deptTrees[i].children.length > 0) {
                            this.searchTree(val, deptTrees[i].children);
                        }
                    }
                }
            }
        },
        mounted() {
            this.initDatas();
        },
        watch: {
            'selectDepts'(val) {
                if (!this.activeSerach) {
                    this.$nextTick(() => {
                        this.activeSerach = true;
                        this.$refs.tree.setCurrentKey(this.$store.getters.user.deptId);
                        this.$store.commit('user/setDeptId', this.$store.getters.user.deptId);
                        this.handleSearch();
                    })
                } else {
                    this.$nextTick(() => {
                        this.activeSerach = true;
                        this.$refs.tree.setCurrentKey(this.$store.state.user.deptId);
                        this.$store.commit('user/setDeptId', this.$store.state.user.deptId);
                    })
                }
            }
        }
    }
</script>
<style scoped lang="less">
    @import "../../../assets/css/common.less";

    .treeTitle {
        background: #f9fafc;
        height: 30px;
        text-align: center;
        line-height: 30px;
    }

    .treeBody {
        min-height: 500px;
        height: 91%;
        padding: 5px 5px;
        margin-bottom: 10px;
        margin-top: -1px;
    }
</style>
